<?php

namespace App\Http\Controllers\WF\Systems;

use DB;
use Config;
use Hash;
use Carbon\Carbon;
use Ramsey\Uuid\Uuid;
use App\Http\Controllers\WF\ApiController;
use Illuminate\Http\Request;
use App\Eloqumd\Wf\WfUser;
use App\Eloqumd\Wf\WfCompany;
use App\Http\Requests\WF\UserRequest;

class UserController extends ApiController
{
    /**
     * 获取用户列表
     *
     * @name    getUserList
     *
     * @return 	array                       返回结果
     */
    public function getUserList(Request $request)
    {
        $page = (int)$request->input('page', 1);
        $limit = $request->input('limit', $this->limit);
        $offest = ($page - 1) * $limit;
        // 关键字
        $keyword = $request->input('keyword', '');
        $orWhere = [];
        $where[] = ['company_id', '=', $this->apiUser['company_id'], 'AND'];
        $where[] = ['isdel', '=', 0, 'AND'];

        if ($this->apiUser['user_type'] == 2) {
            $where[] = ['user_type', '=', 2, 'AND'];
        }

        if ($keyword) {
            $orWhere[] = ['name', 'like', "%{$keyword}%", 'AND'];
            $orWhere[] = ['email', 'like', "%{$keyword}%", 'OR'];
            $orWhere[] = ['idcard', 'like', "%{$keyword}%", 'OR'];
            $orWhere[] = ['mobile', 'like', "%{$keyword}%", 'OR'];
            $orWhere[] = ['realname', 'like', "%{$keyword}%", 'OR'];
        }

        $totalCount = WfUser::where($where)
            ->where(function ($query) use ($orWhere) {
                if ($orWhere) $query->orWhere($orWhere);
            })->count();
        $listData = WfUser::where($where)
            ->where(function ($query) use ($orWhere) {
                if ($orWhere) $query->orWhere($orWhere);
            })
            ->offset($offest)
            ->limit($limit)
            ->orderBy('created_at', 'asc')
            ->get()
            ->toArray();

        foreach ($listData as $k => $v) {
            $listData[$k]['parent_name'] = WfCompany::where('id', $v['parent_id'])->value('name');
            unset($listData[$k]['solt']);
            unset($listData[$k]['password']);
            // unset($listData[$k]['role']);
            unset($listData[$k]['auth']);
        }

        $jsonData = [
            'list' => array_values($listData),
            'count' => $totalCount
        ];

        return $this->jsonReturns(10000, $this->success, $jsonData);
    }

    /**
     * 添加用户
     *
     * @name    userCrd
     *
     * @return 	array                       返回结果
     */
    public function userCrd(UserRequest $request)
    {
        $request->validate('crd');
        $param = $request->all();

        DB::beginTransaction();
        try {
            $model = new WfUser;
            $model->name = $param['name'];
            $model->email = $param['email'];
            $model->idcard = $param['idcard'];
            $model->mobile = $param['mobile'];
            $model->realname = $param['realname'];
            $model->avatar = $param['avatar'] ?? '';
            $role = $param['role'] ?? [];
            $model->role = empty($role) ? '' : implode(',', $role);
            $initPwd = Config::get('api.jishulin_init_pwd');
            $userSolt = Uuid::uuid1()->getHex();
            $model->solt = $userSolt;
            $model->password = Hash::make($initPwd, ['solt' => $userSolt]);
            $model->status = $param['status'];
            $model->user_type = 2;
            $model->company_id = $this->apiUser['company_id'];
            $model->parent_id = $param['parent_id'];
            $model->created_at = Carbon::now();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage());
        }
    }

    /**
     * 通过ID获取用户详情
     *
     * @name    getUserById
     *
     * @return 	array                       返回结果
     */
    public function getUserById(Request $request)
    {
        $id = $request->input('id', 0);
        $data = WfUser::find($id)->toArray();
        unset($data['password']);
        unset($data['solt']);

        return $this->jsonReturns(10000, $this->success, $data);
    }

    /**
     * 删除用户
     *
     * @name    userRmv
     *
     * @return 	array                       返回结果
     */
    public function userRmv(Request $request)
    {
        $id = $request->input('id');

        DB::beginTransaction();
        try {
            $model = WfUser::find($id);
            $model->isdel = 1;
            $model->deleted_at = time();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage());
        }
    }

    /**
     * 启用禁用用户
     *
     * @name    userSts
     *
     * @return 	array                       返回结果
     */
    public function userSts(Request $request)
    {
        $id = $request->input('id');
        $status = $request->input('status', 0);

        DB::beginTransaction();
        try {
            $model = WfUser::find($id);
            $model->status = $status;
            $model->updated_at = Carbon::now();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage());
        }
    }

    /**
     * 编辑用户
     *
     * @name    userEdt
     *
     * @return 	array                       返回结果
     */
    public function userEdt(UserRequest $request)
    {
        $request->validate('edt');
        $param = $request->all();

        if (WfUser::where('mobile', $param['mobile'])->where('id', '<>', $param['id'])->count()) {
            return $this->jsonReturns(50000, trans('wf.WF-User-Mobile-Has-Exists'));
        }
        if (WfUser::where('email', $param['email'])->where('id', '<>', $param['id'])->count()) {
            return $this->jsonReturns(50000, trans('wf.WF-User-Email-Has-Exists'));
        }

        DB::beginTransaction();
        try {
            $model = WfUser::find($param['id']);
            $model->email = $param['email'];
            $model->mobile = $param['mobile'];
            $model->realname = $param['realname'];
            $model->avatar = $param['avatar'] ?? '';
            $role = $param['role'] ?? [];
            $model->role = empty($role) ? '' : implode(',', $role);
            $model->status = $param['status'];
            $model->updated_at = Carbon::now();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage());
        }
    }
    
    /**
     * 重置密码
     *
     * @name    userRepwd
     *
     * @return 	array                       返回结果
     */
    public function userRepwd(Request $request)
    {
        $id = $request->input('id');
        
        DB::beginTransaction();
        try {
            $model = WfUser::find($id);
            $initPwd = Config::get('api.jishulin_init_pwd');
            $userSolt = Uuid::uuid1()->getHex();
            $model->solt = $userSolt;
            $model->password = Hash::make($initPwd, ['solt' => $userSolt]);
            $model->save();
        
            DB::commit();
        
            return $this->jsonReturns(10000, $this->success);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage());
        }
    }
}
